import { ref } from "vue";
import { ContractTeam } from "@/models/dataPeople/ContractTeam";
import api from "@/utils";
import { SelectedPropMap } from "@/components/input/SelectedPropMap";

/**
 * 用于处理选择框选择后的数据联动.
 * @param url 查询数据的url
 * @param selectedPropMap 联动的值
 * @constructor
 */
export function AutocompleteInputEventArray(
  url: string,
  selectedPropMap: SelectedPropMap
) {
  const selectedList = ref([]);

  const getRecords = (callback: (value: ContractTeam[]) => void) => {
    api.http.get(url).then((res) => {
      selectedList.value = res.data;
      callback(res.data);
    });
  };

  const selectedRow = ref();

  /**
   * @param setProp 需要绑定的数据在表单中的字段名.
   * @param setOriginProp 需要绑定的数据在原数据中的字段名.
   * @param selectedProp 搜索框选中的数据在表单中的字段名.
   * @param subJsonItem
   */
  const setSelectRowData = (
    setProp: string,
    setOriginProp: string,
    selectedProp: string,
    subJsonItem: Record<string, unknown>
  ) => {
    const selectRows = selectedList.value.filter((item) => {
      return (
        item[selectedPropMap.selectedOriginProp] === subJsonItem[selectedProp]
      );
    });
    if (selectRows.length === 1) {
      selectedRow.value = selectRows[0];
      subJsonItem[setProp] = selectedRow.value[setOriginProp];
      return subJsonItem;
    } else {
      return "";
    }
  };
  return {
    getRecords,
    setSelectRowData,
  };
}
